package org.xg.utils;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;

import com.googlecode.genericdao.search.Search;
import com.googlecode.genericdao.search.SearchResult;
import com.googlecode.genericdao.search.Sort;

public class PageUtils {

	public static Search initPageFromExtGridParam(final HttpServletRequest request){
		Search search = new Search();
		String startStr = request.getParameter("start");
		String limitStr = request.getParameter("limit");
		String sort = request.getParameter("sort");		//ext4 表格 排序字符串
		
		int start = 0;
		if( StringUtils.isNotBlank(startStr)){
			start = Integer.parseInt(startStr);
		}
		search.setFirstResult(start);
		
		int limit = 0;
		if(StringUtils.isNotBlank(limitStr)){
			limit = Integer.parseInt(limitStr);
		}
		search.setMaxResults(limit);
		
		if (StringUtils.isNotEmpty(sort)) {
			Sort[] sorts = toSorts(sort);
			search.addSorts(sorts);
		}
		return search;
	}
	
	/**
	 * @desc Ext 解析排序字符串
	 * @param jsonSorts  [{"property":"domainName","direction":"ASC"}]
	 * @return
	 */
	private static Sort[] toSorts(String jsonSorts){
		JSONArray jsonArray = JSONArray.fromObject(jsonSorts);
		Sort[] sorts = new Sort[jsonArray.size()];
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			String sort = jsonObject.get("property").toString();
			String dir = jsonObject.get("direction").toString();
			Sort sortField = new Sort();
			sortField.setProperty(sort);
			if(dir != null && (dir.equalsIgnoreCase("desc"))){
				sortField.setDesc(true);
			}
			sortField.setIgnoreCase(true);
			sorts[i] = sortField;
		}
		return sorts;
	}
	
	/**
	 * 把查询结果转换为Map, list为结果集，totalCount为总数
	 * @param searchResult
	 * @return
	 * @throws Exception
	 */
	public static  Map<String,Object> convertSearchResultToMap(SearchResult<?> searchResult) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("list", searchResult.getResult());
		resultMap.put("totalCount", searchResult.getTotalCount());
		return resultMap;
	}
}
